package cn.sinata.wanglin.property.activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.ImagePagerActivity;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.BitmapUtils;
import com.xilada.xldutils.utils.FileUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.TwoTextLinearView;
import com.xilada.xldutils.xldUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.Image;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class PropertyRepairActivity extends TitleActivity {
    @BindView(R.id.rv_towhere)
    RecyclerView rv_towhere ;//
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.ttlv_choicetime)
    TwoTextLinearView ttlv_choicetime;
    BaseRecyclerAdapter currentlableAdapter;
    private ArrayList<Project> mcurrentlabledatas=new ArrayList<>();
    private String userId ;
    private String housingId ;
    private BaseRecyclerAdapter<Image> imageBaseRecyclerAdapter;
    private ArrayList<Image> mImageInfos = new ArrayList<>();
    private final int MAX_NUMBER = 4;
    private String time;
    private String project;

    @Override
    protected int setContentId() {
        return R.layout.activity_propertyrepair;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("物业报修");

        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        housingId = MyApplication.houseid;

        addRightButton("报修记录", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtil.create(mContext)
                        .go(RepairRecordsActivity.class)
                        .start();
            }
        });
        mcurrentlabledatas.add(new Project("管道疏通"));
        mcurrentlabledatas.add(new Project("水电维修"));
        mcurrentlabledatas.add(new Project("房屋维修"));
        mcurrentlabledatas.add(new Project("开锁换锁"));
        mcurrentlabledatas.add(new Project("线路维修"));
        mcurrentlabledatas.add(new Project("\u3000其他\u3000"));
        if(currentlableAdapter==null){
            GridLayoutManager mgr=new GridLayoutManager(this,4);
            rv_towhere.setLayoutManager(mgr);
            currentlableAdapter=new BaseRecyclerAdapter<Project>(mcurrentlabledatas,R.layout.item_choose_project) {
                @Override
                public void onBind(final int position, final Project data, ViewHolder holder) {
                    Utils.systemErr("0000---->"+position+data.isSelected());
                    TextView view = holder.bind(R.id.cb_samecitylable);
                    view.setText(data.getName());
                    view.setSelected(data.isSelected());
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            boolean isSelect = v.isSelected();
                            if (isSelect) {
                                resetAll();
                                project = "";
                            } else {
                                project = data.getName();
                            }
                            data.setSelected(!isSelect);
                            notifyDataSetChanged();
                        }
                    });
                }

                private void resetAll(){
                    for (Project project1 : mData) {
                        project1.setSelected(false);
                    }
                }
            };
            rv_towhere.setAdapter(currentlableAdapter);
        }

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        addDefault();
        initAdapter();
    }

    void addDefault() {
        Image image = new Image();
        image.setUrl("add");
        mImageInfos.add(image);
    }

    void initAdapter() {
        imageBaseRecyclerAdapter = new BaseRecyclerAdapter<Image>(mImageInfos, R.layout.item_myimage_grid) {
            @Override
            public void onBind(final int position, Image image, ViewHolder holder) {
                if ("add".equals(image.getUrl())) {
                    ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("res://mipmap/" + R.mipmap.ic_addimage));
                    holder.bind(R.id.iv_deletemyimg).setVisibility(View.GONE);
                    holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            selectImages();
                        }
                    });
                } else {
                    ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("file://" + image.getUrl()));
                    holder.bind(R.id.iv_deletemyimg).setVisibility(View.VISIBLE);
                    holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            int current = position;
                            ArrayList<String> showPhoto = new ArrayList<String>();
                            for (int i = 0; i < mData.size(); i++) {
                                if (!"add".equals(mData.get(i).getUrl())) {
                                    showPhoto.add("file://"+mData.get(i).getUrl());
                                } else {
                                    current--;
                                }

                            }
                            ActivityUtil.create(mContext).go(ImagePagerActivity.class)
                                    .put(ImagePagerActivity.URLS, showPhoto)
                                    .put(ImagePagerActivity.CURRENT_POSITION, current)
                                    .start();
                        }
                    });
                    holder.bind(R.id.iv_deletemyimg).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (mData.size() == 9 && !"add".equals(mData.get(0).getUrl())) {
                                mData.remove(position);
                                Image img = new Image();
                                img.setUrl("add");
                                mData.add(0, img);
                            } else {
                                mData.remove(position);
                            }
                            notifyDataSetChanged();
                        }
                    });
                }
            }
        };
        mRecyclerView.setAdapter(imageBaseRecyclerAdapter);
    }

    private void selectImages() {
        ArrayList<String> images = new ArrayList<>();
        if (mImageInfos.size() > 1) {
            for (int i = 1; i < mImageInfos.size(); i++) {
                images.add(mImageInfos.get(i).getUrl());
            }
        }
//        int maxNumber = MAX_NUMBER - mImageInfos.size() + 1;
        ActivityUtil activityUtil = ActivityUtil.create(mContext).go(MultiImageSelectorActivity.class)
                .put(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, MAX_NUMBER)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        if (images.size() > 0) {
            activityUtil.put(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, images);
        }
        activityUtil.startForResult(3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 3 ) {
                if (data == null) {
                    return;
                }
//                int maxNumber = MAX_NUMBER - mImageInfos.size() + 1;
                ArrayList<String> resultList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                mImageInfos.clear();
                if (MAX_NUMBER != resultList.size()) {
                    addDefault();
                }
                for (String s : resultList) {
                    Image image = new Image();
                    image.setUrl(s);
                    mImageInfos.add(image);
                }
                imageBaseRecyclerAdapter.notifyDataSetChanged();
            } else if (requestCode == 10) {
                if (data == null) {
                    return;
                }
                time = data.getStringExtra("time");
                ttlv_choicetime.setRightText(time);
            }
        }
    }

    void uploadData(final String content){
        if (TextUtils.isEmpty(project)) {
            showToast("请选择一个报修项目");
            return;
        }
        if (TextUtils.isEmpty(content)) {
            showToast("请描述一下报修问题");
            return;
        }
        if (TextUtils.isEmpty(time)) {
            showToast("请选择预约时间");
            return;
        }
        showDialog();
        if (mImageInfos.size() > 1) {
            uploadHasImage(content);
        } else {
            uploadNoImage(content);
        }
    }

    void uploadNoImage(final String content){
        HttpManager.addRepair(userId,housingId,content,project,time,null)
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        showToast(msg);
                        finish();
                    }
                });
    }

    void uploadHasImage(final String content){
        final ArrayList<Image> images = new ArrayList<>();
        if (mImageInfos.size() == MAX_NUMBER) {
            if (mImageInfos.get(0).getUrl().equals("add")) {
                images.addAll(mImageInfos.subList(1, mImageInfos.size()));
            } else {
                images.addAll(mImageInfos);
            }
        } else {
            images.addAll(mImageInfos.subList(1,mImageInfos.size()));
        }
        Utils.systemErr(images);
        Observable.from(images)
                .subscribeOn(Schedulers.io())
                .map(new Func1<Image, BitmapUtils.Image>() {
                    @Override
                    public BitmapUtils.Image call(Image image) {
                        return BitmapUtils.compressImage(image.getUrl());
                    }
                })
                .flatMap(new Func1<BitmapUtils.Image, Observable<String>>() {
                    @Override
                    public Observable<String> call(BitmapUtils.Image image) {
                        return HttpManager.uploadFile(mContext,new File(image.getPath()));
                    }
                })
                .toList()
                .flatMap(new Func1<List<String>, Observable<ResultData<JsonObject>>>() {
                    @Override
                    public Observable<ResultData<JsonObject>> call(List<String> strings) {
                        StringBuilder builder = new StringBuilder();
                        builder.append("[");
                        for (String string : strings) {
                            builder.append("{\"img\":\"");
                            builder.append(string);
                            //这里的图片不需要显示，scale设置默认值。
                            builder.append("\",\"scale\":1}");
                            builder.append(",");
                        }
                        if (builder.length() > 1) {
                            builder.deleteCharAt(builder.length()-1);
                        }
                        builder.append("]");
                        String imgList = builder.toString();
                        Utils.systemErr(imgList);
                        return HttpManager.addRepair(userId,housingId,content,project,time,imgList);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        showToast(msg);
                        finish();
                    }
                });
    }

    @OnClick({R.id.tv_action,R.id.ttlv_choicetime})
    void onClick(View v){
        switch (v.getId()) {
            case R.id.tv_action:
                String content = et_content.getText().toString().trim();
                uploadData(content);
                break;
            case R.id.ttlv_choicetime:
                ActivityUtil.create(this)
                        .go(ChooseTimeDialogActivity.class)
                        .startForResult(10);
                break;
        }
    }

    private class Project {
        private String name;
        private boolean isSelected = false;

        public Project(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }

    @Override
    public void finish() {
        if (!TextUtils.isEmpty(xldUtils.PICDIR)) {
            FileUtils.deleteFiles(new File(xldUtils.PICDIR));
        }
        super.finish();
    }
}
